package com.power.sifa.correction.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.cache.redis.RedisCacheUtil;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.correction.dao.Cre_record_gaDao;
import com.power.sifa.correction.model.*;
import com.power.sifa.correction.model.enumeration.St_deal;
import com.power.sifa.correction.model.enumeration.Tp_crc_ruleEnum;
import com.power.sifa.correction.model.pageInfo.Cre_record_gaPageInfo;
import com.power.sifa.correction.model.pojo.bo.CheckRuleRequestBO;
import com.power.sifa.correction.model.pojo.bo.CheckRuleResultBO;
import com.power.sifa.correction.model.pojo.bo.Crc_departBO;
import com.power.sifa.correction.model.pojo.bo.SameCasePersonBO;
import com.power.sifa.correction.service.*;
import com.power.sifa.runner.jobs.WarningThread;
import com.power.sifa.statistics.model.vo.MarkPointVO;
import com.power.sifa.statistics.model.vo.MonitoringVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 *  公安推送记录业务层实现
 */
@Service
@Slf4j
public class Cre_record_gaServiceImpl extends BaseServiceImpl implements Cre_record_gaService {

//    @Resource
//    private Cre_record_gaServiceImpl service;
    @Resource
    private Crc_personService crc_personService;
    @Resource
    private Crc_groupService crc_groupService;
    @Resource
    private Crc_group_personService crc_group_personService;
    @Resource
    private Crw_rule_personService crw_rule_personService;
    @Resource
    private Crw_rule_groupService crw_rule_groupService;
    @Resource
    private RuleRecordCacheService ruleRecordCacheService;
    @Resource
    private RuleHandleService ruleHandleService;
    @Resource
    private  Cre_warningService cre_warningService;
    @Resource
    private  Cre_warning_detailService cre_warning_detailService;
    @Resource
    private Cre_workService cre_workService;
    @Resource
    private Crc_cameraService crc_cameraService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private Ha_attachmentService haAttachmentService;

    /**
     * redis 存储key, 加上人员id
     */
    private static final String REDIS_KEY = "CORRECTPERSON:";

    @Resource
    private Cre_record_gaDao dao;

    @Override
    public Cre_record_ga getById(Integer id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Cre_record_ga cre_record_ga) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (cre_record_ga.getPrimaryKey() != null) {
        	 Cre_record_ga cre_record_gafDb = dao.findById(cre_record_ga.getPrimaryKey()).orElse(null);
             if(cre_record_gafDb != null) {
                BeanUtils.copyProperties(cre_record_ga, cre_record_gafDb);
                dao.save(cre_record_gafDb);
                return;
             }
        }
        dao.save(cre_record_ga);
    }

    @Override
    public void removeById(Integer id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Cre_record_ga> findAll(Cre_record_gaPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
	public List<Cre_record_ga> findAll() {
		return dao.findAll();
	}

    @Override
    public List<Cre_record_ga> findByConditon(Cre_record_gaPageInfo pageInfo) {
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec);
    }

    @Override
	public void saveAll(List<Cre_record_ga> list) {
		dao.saveAll(list);
	}


    /**
     * 同案犯规则对应的人员及公安数据查询
     *
     * @param sameCaseRuleSet    同案犯规则集合
     * @param sameCasePersonSet  同案犯人员集合
     * @param checkRuleRequestBO
     * @return
     */
    private List<SameCasePersonBO> sameCaseBaseDataInit(Set<String> sameCaseRuleSet, Set<String> sameCasePersonSet, CheckRuleRequestBO checkRuleRequestBO) {
        // 聚集规则人群数据
        List<SameCasePersonBO> sameCasePersonList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(sameCaseRuleSet) && CollectionUtil.isNotEmpty(sameCasePersonSet)) {
            List<Crw_rule_samecase> allSamecaseRules = checkRuleRequestBO.getSameCaseRules();
            List<String> allPersonList = sameCasePersonSet.stream().collect(Collectors.toList());
            List<Crc_person> allPersonInfoList = crc_personService.findByPersonIds(allPersonList);
            // 查询全部的同案人员信息
            for (String sameCaseRuleId : sameCaseRuleSet) {
                // 查询对应的规则
                Crw_rule_samecase samecaseRule = allSamecaseRules.stream().filter(element -> element.getId().equals(sameCaseRuleId)).findFirst().orElse(null);
                if (ObjectUtil.isNotNull(samecaseRule) && ObjectUtil.isNotNull(samecaseRule.getRange_time())) {
                    // 时间范围
                    Date endTime = checkRuleRequestBO.getRectime();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(endTime);
                    calendar.add(Calendar.MINUTE, -samecaseRule.getRange_time());
                    Date startTime = calendar.getTime();

                    // 查询当前时间范围的公安人员数据
                    List<Cre_record_ga> record_gas = this.findRecordByPersonIdsAndTime(allPersonList, startTime, endTime);
                    // 按照人员id进行分组
                    Map<String, List<Cre_record_ga>> record_gasGroup = record_gas.stream().filter(element -> StringUtils.isNotEmpty(element.getPerid()))
                            .collect(Collectors.groupingBy(element -> element.getPerid()));

                    if (ObjectUtil.isNotNull(record_gasGroup)) {
                        for (String sameCasePersonId : sameCasePersonSet) {
                            // 查询公安数据
                            List<Cre_record_ga> record_gas_person = record_gasGroup.get(sameCasePersonId);
                            // 查询人员信息
                            Crc_person personInfo = allPersonInfoList.stream().filter(element -> element.getId().equals(sameCasePersonId)).findFirst().orElse(null);
                            sameCasePersonList.add(SameCasePersonBO.builder().perId(sameCasePersonId).personInfo(personInfo).ruleId(sameCaseRuleId).re_record_gas(record_gas_person).build());
                        }
                    }

                }
            }
        }
        return sameCasePersonList;
    }

    /**
     * 同案犯规去重设置
     * @param checkRuleRequestBO
     */
    private void sameCaseRuleDistinct (CheckRuleRequestBO checkRuleRequestBO) {
        Set<String> sameCaseRuleSet = CollectionUtil.isNotEmpty(checkRuleRequestBO.getSameCaseRules()) ?
                checkRuleRequestBO.getSameCaseRules().stream().map(Crw_rule_samecase::getId).collect(Collectors.toSet()) : new HashSet<>();
        Set<String> sameCasePersonSet = new HashSet<>();
        // 通过规则查询人员人群数据
        if (CollectionUtil.isNotEmpty(sameCaseRuleSet)) {
            for (String sameCaseRuleId : sameCaseRuleSet) {
                // 查询全部的人员及人群
                List<String> sameCasePersons = this.crw_rule_personService.findPersonIdsByRuleId(sameCaseRuleId);
                // 人群
                List<String> sameCaseGroup = this.crw_rule_groupService.findGroupIdsByRuleId(sameCaseRuleId);
                // 通过人群查询对应的人员数据
                sameCasePersonSet = sameCasePersons.stream().collect(Collectors.toSet());
                if (CollectionUtil.isNotEmpty(sameCaseGroup)) {
                    List<Crc_group> groups = this.crc_groupService.findByGroupIds(sameCaseGroup);
                    List<String> groupIds = groups.stream().map(Crc_group::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(groups)) {
                        List<Crc_group_person> personList = this.crc_group_personService.findPersonByGroupIds(groupIds);
                        Set<String> group_personsSet = personList.stream().map(Crc_group_person::getPerid).collect(Collectors.toSet());
                        sameCasePersonSet.addAll(group_personsSet);
                    }
                }
            }
        }
        // 通过规则查询对应人员时间范围的公安数据
        checkRuleRequestBO.setSameCasePersonList(sameCaseBaseDataInit(sameCaseRuleSet, sameCasePersonSet, checkRuleRequestBO));
    }

    /**
     * 初始化人员的查询参数比如规则和分组等信息
     * @param cre_record_ga
     * @param checkRuleRequestBO
     * @throws Exception
     */
    private void initRuleAndGroupData(Cre_record_ga cre_record_ga, CheckRuleRequestBO checkRuleRequestBO) throws Exception {
        // 通过人员id查询当前人员的人员信息及分组信息
        String perid = cre_record_ga.getPerid();
        final String redisKey = REDIS_KEY + perid;
        try {
//            if (redisCacheUtil.hasKey(redisKey)) {
//                log.info("当前人员数据{}存在redis缓存", perid);
//                log.info("缓存数据如下：{}", JSON.toJSONString(redisCacheUtil.get(redisKey)));
//                CheckRuleRedisBO redisData = JSON.parseObject(JSON.toJSONString(redisCacheUtil.get(redisKey)), CheckRuleRedisBO.class);
//                checkRuleRequestBO.setPersonInfo(redisData.getPersonInfo());
//                checkRuleRequestBO.setGroupList(redisData.getGroupList());
//                checkRuleRequestBO.setDisabledRules(redisData.getDisabledRules());
//                checkRuleRequestBO.setZoneInRules(redisData.getZoneInRules());
//                checkRuleRequestBO.setZoneOutRules(redisData.getZoneOutRules());
//                checkRuleRequestBO.setNightOutRules(redisData.getNightOutRules());
//                checkRuleRequestBO.setSameCaseRules(redisData.getSameCaseRules());
//                log.info("redis缓存数据设置完成");
//            } else {
//                log.info("当前人员数据{}不存在redis缓存数据",perid);
                // 查询规则数据
                ruleRecordCacheService.initValidateRule(perid, checkRuleRequestBO);
//                log.info("当前人员规则数据如下{}", JSON.toJSONString(checkRuleRequestBO));
//                // 记录当前的缓存数据，有效期设置为30分钟
//                redisCacheUtil.set(redisKey, checkRuleRequestBO, 1000L);
//                log.info("当前人员redis缓存数据记录如下", JSON.toJSONString(checkRuleRequestBO));
//            }

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    /**
     * 公安记录查询单条对应的校验规则记录
     * @param cre_record_ga 公安记录
     * @param checkRuleRequestBOList 对应人员的总的校验请求list
     * @return
     * @throws Exception
     */
    @Override
    public List<CheckRuleResultBO> transSingleRuleRequest(Cre_record_ga cre_record_ga, List<CheckRuleRequestBO> checkRuleRequestBOList) throws Exception {
        CheckRuleRequestBO checkRuleRequestBO = BeanUtil.toBean(cre_record_ga, CheckRuleRequestBO.class);
        checkRuleRequestBO.setId(cre_record_ga.getId());
        if (ObjectUtil.isNotNull(cre_record_ga) && StringUtils.isNotEmpty(cre_record_ga.getPerid())) {
            // 通过人员id查询当前人员的人员信息及分组信息
            try {
                initRuleAndGroupData(cre_record_ga, checkRuleRequestBO);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("当前人员" + cre_record_ga.getId() + "初始化规则数据异常");
                return Collections.emptyList();
            }
            // 查询当前的特殊人群聚集规则
            // FEAT: 同案犯聚集规则去除，但是保留考虑后续会要求加上
            // sameCaseRuleDistinct(checkRuleRequestBO);

            // 进行规则校验
            List<CheckRuleResultBO> checkRuleResultList = ruleHandleService.ruleValidate(checkRuleRequestBO);
            // 记录请求数据到请求总表中
            checkRuleRequestBOList.add(checkRuleRequestBO);
            return checkRuleResultList;
        }
        return Collections.emptyList();
    }

    @Override
    public void transRuleRequests(List<Cre_record_ga> cre_record_gas) throws Exception {
        // 进行过滤和排序
        List<Cre_record_ga> filterCre_record_gas = cre_record_gas.stream()
                .filter(el -> ObjectUtil.isNotNull(el.getPerid())
                && ObjectUtil.isNotNull(el.getRectime())
                        && ObjectUtil.isNotNull(el.getLatcamera())
                        && ObjectUtil.isNotNull(el.getLngcamera()))
                .sorted(Comparator.comparing(Cre_record_ga::getRectime))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(filterCre_record_gas)) {
            // 生成对应的摄像头数据 开启新线程查询对应的摄像头数据
            CompletableFuture.runAsync(() -> crc_cameraService.generateCameraInfo(filterCre_record_gas));
            // 公安推送数据按照人员区分
            Map<String, List<Cre_record_ga>> cre_record_gasMap = filterCre_record_gas.stream().collect(Collectors.groupingBy(Cre_record_ga::getPerid));
            try {
                if (ObjectUtil.isNotNull(cre_record_gasMap)) {
                    for (String perId : cre_record_gasMap.keySet()) {
                        List<Cre_record_ga> cre_record_gaPersonsList = cre_record_gasMap.get(perId);
                        try {
                            List<CheckRuleRequestBO> allCheckRuleRequests = new ArrayList<>();
                            List<CheckRuleResultBO> allCheckResults = new ArrayList<>();
                            for (Cre_record_ga record_ga : cre_record_gaPersonsList) {
                                try {
                                    List<CheckRuleResultBO> checkRuleResultList = transSingleRuleRequest(record_ga, allCheckRuleRequests);
                                    if (CollectionUtil.isNotEmpty(checkRuleResultList)) {
                                        allCheckResults.addAll(checkRuleResultList);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.error("当前记录" + record_ga.getId() + "校验异常");
                                }
                            }
                            // 规则校验结果进行分类及去重
                            Map<Integer, List<CheckRuleResultBO>> checkRuleResultGroups = splitCheckResult(allCheckResults);
                            // 进行预警信息去重 及 详情信息保存
                            this.saveWarningInfo(perId, allCheckRuleRequests, checkRuleResultGroups);
                        }  catch (Exception e) {
                            e.printStackTrace();
                            log.error("当前人员" + perId + "校验数据保存异常");
                        } finally {
                            // 更新数据的状态
                            cre_record_gaPersonsList.stream().forEach(el -> {
                                el.setStatus(St_deal.YES);
                            });
                            this.saveAll(cre_record_gaPersonsList);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 规则校验结果按照规则进行分类
     * @param checkRuleResultList 单个人员的全部校验结果
     * @return
     */
    private Map<Integer, List<CheckRuleResultBO>> splitCheckResult(List<CheckRuleResultBO> checkRuleResultList) {
        Map<Integer, List<CheckRuleResultBO>> checkRuleResultGroups = new HashMap<>();
        if (CollectionUtil.isNotEmpty(checkRuleResultList)) {
            checkRuleResultList.stream().forEach(element -> {
                if (StringUtils.isNotEmpty(element.getRuleId())) {
                    String firstLetter = element.getRuleId().substring(0, 1).toUpperCase(Locale.ROOT);
                    switch (firstLetter) {
                        case "A":
                            List<CheckRuleResultBO> zoneOutRuleResults = CollectionUtil.isNotEmpty(checkRuleResultGroups.get(Tp_crc_ruleEnum.ZONE_OUT_RULE.getId())) ?
                                    checkRuleResultGroups.get(Tp_crc_ruleEnum.ZONE_OUT_RULE.getId()) : new ArrayList<>();
                            zoneOutRuleResults.add(element);
                            checkRuleResultGroups.put(Tp_crc_ruleEnum.ZONE_OUT_RULE.getId(), zoneOutRuleResults);
                            break;
                        case "B":
                            List<CheckRuleResultBO> zoneInRuleResults = CollectionUtil.isNotEmpty(checkRuleResultGroups.get(Tp_crc_ruleEnum.ZONE_IN_RULE.getId())) ?
                                    checkRuleResultGroups.get(Tp_crc_ruleEnum.ZONE_IN_RULE.getId()) : new ArrayList<>();
                            zoneInRuleResults.add(element);
                            checkRuleResultGroups.put(Tp_crc_ruleEnum.ZONE_IN_RULE.getId(), zoneInRuleResults);
                            break;
                        case "C":
                            List<CheckRuleResultBO> nightOutRuleResults = CollectionUtil.isNotEmpty(checkRuleResultGroups.get(Tp_crc_ruleEnum.NIGHT_OUT_RULE.getId())) ?
                                    checkRuleResultGroups.get(Tp_crc_ruleEnum.NIGHT_OUT_RULE.getId()) : new ArrayList<>();
                            nightOutRuleResults.add(element);
                            checkRuleResultGroups.put(Tp_crc_ruleEnum.NIGHT_OUT_RULE.getId(), nightOutRuleResults);
                            break;
                          // FEAT: 去除同案犯聚集规则， 保留避免后续撤回
//                        case "D":
//                            List<CheckRuleResultBO> sameCaseRuleResults = CollectionUtil.isNotEmpty(checkRuleResultGroups.get(Tp_crc_ruleEnum.SAME_CASE_RULE.getId())) ?
//                                    checkRuleResultGroups.get(Tp_crc_ruleEnum.SAME_CASE_RULE.getId()) : new ArrayList<>();
//                            sameCaseRuleResults.add(element);
//                            checkRuleResultGroups.put(Tp_crc_ruleEnum.SAME_CASE_RULE.getId(), sameCaseRuleResults);
//                            break;
                    }
                }
            });
        }
        return checkRuleResultGroups;
    }

    /**
     * 通过预警信息的坐标范围查询对应的司法所地址信息
     * @param perid
     * @return
     */
    private Crc_departBO findWarnPersonBelongDepart(String perid) {
        // 设置当前的数据
        if (StringUtils.isNotEmpty(perid)) {
            List<Crc_departBO> departLists = this.crc_personService.findDepartByPersons(Collections.singletonList(perid));
            if (CollectionUtil.isNotEmpty(departLists)) {
                return departLists.stream().filter(el -> ObjectUtil.isNull(el.getFid())).findFirst().orElse(null);
            }
        }
        return null;
    }


    /**
     * 保存规则校验预警数据及详情数据
     * @param checkRuleRequests 单个人员的全部请求数据
     * @param checkRuleResultGroups 单人人员的全部校验结果
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWarningInfo(String perid, List<CheckRuleRequestBO> checkRuleRequests,
                                Map<Integer, List<CheckRuleResultBO>> checkRuleResultGroups) {
        if (ObjectUtil.isNotNull(checkRuleResultGroups)) {
            // 进行分类
            for (Integer ruleType : checkRuleResultGroups.keySet()) {
                List<CheckRuleResultBO> checkRuleResultGroupList = checkRuleResultGroups.get(ruleType);
                // 按照时间正序排序
                checkRuleResultGroupList = checkRuleResultGroupList.stream().filter(el -> ObjectUtil.isNotNull(el.getRectime())).sorted(Comparator.comparing(CheckRuleResultBO::getRectime)).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(checkRuleResultGroupList) && CollectionUtil.isNotEmpty(checkRuleRequests)) {
                    // 根据坐标点进行分组
                    Map<String, List<CheckRuleResultBO>> resultResultMap = checkRuleResultGroupList.stream().collect(
                        Collectors.groupingBy(ruleResult -> ruleResult.getLatcamera().toString() + '-' + ruleResult.getLngcamera().toString()));
                    if (ObjectUtil.isNotNull(resultResultMap)) {
                        for (String key : resultResultMap.keySet()) {
                            List<CheckRuleResultBO> resultResultMapList = resultResultMap.get(key);
                            // 拿取第一条数据
                            CheckRuleResultBO baseCheckRuleResult = resultResultMapList.get(0);
                            CheckRuleRequestBO checkRuleRequest = checkRuleRequests.stream().filter(el -> el.getId().equals(baseCheckRuleResult.getGaid())).findAny().orElse(checkRuleRequests.get(0));
                            Cre_warning cre_warning = new Cre_warning(checkRuleRequest, baseCheckRuleResult);
                            List<String> allDescribeList = new ArrayList<>();
                            resultResultMapList.stream().forEach(el -> allDescribeList.addAll(el.getDescribeList()));
                            if (CollectionUtil.isNotEmpty(allDescribeList)) {
                                cre_warning.setDescribe(String.join(",", allDescribeList));
                            }
                            // 进行当前失效规则排除校验
                            // 保存预警数据
                            cre_warningService.saveOrUpdate(cre_warning);
                            try {
                                // 查询当前的预警信息范围处于哪个司法所
                                Crc_departBO depart = findWarnPersonBelongDepart(perid);
                                // 保存对应的预警处置任务
                                Cre_work cre_work = new Cre_work(cre_warning, depart);
                                // 发送消息, 保存赣政通待办id
                                String todoid = this.crc_personService.sendMessage(perid, cre_warning.getId(), cre_work.getId(), cre_warning.getType());
                                cre_work.setTodoid(todoid);
                                cre_workService.saveOrUpdate(cre_work);
                            } catch (Exception e) {
                                log.error("社矫功能发送赣政通待办异常：{},{}", perid, cre_warning.getGaid());
                            }

                            // 保存详情数据
                            cre_warning_detailService.saveAll(Cre_warning_detail.convertToList(cre_warning, resultResultMapList));
                        }
                    }

//                    List<Cre_warning> warnings = new ArrayList<>();
//                    checkRuleResultGroupList.stream().forEach(baseCheckRuleResult -> {
//                        CheckRuleRequestBO checkRuleRequest = checkRuleRequests.stream().filter(el -> el.getId().equals(baseCheckRuleResult.getGaid())).findAny().orElse(checkRuleRequests.get(0));
//                        Cre_warning cre_warning = new Cre_warning(checkRuleRequest, baseCheckRuleResult);
//                        warnings.add(cre_warning);
//                    });
//                    Cre_warning cre_warning = warnings.get(0);
//                    List<String> allDescribeList = new ArrayList<>();
//                    checkRuleResultGroupList.stream().forEach(el -> allDescribeList.addAll(el.getDescribeList()));
//                    if (CollectionUtil.isNotEmpty(allDescribeList)) {
//                        cre_warning.setDescribe(String.join(",", allDescribeList));
//                    }
//                    // 进行当前失效规则排除校验
//                    // 保存预警数据
//                    cre_warningService.saveAll(warnings);
//                    // 查询当前的预警信息范围处于哪个司法所
//                    Crc_departBO depart = findWarnPersonBelongDepart(perid);
//                    // 保存详情数据
//                    cre_warning_detailService.saveAll(Cre_warning_detail.convertToList(cre_warning, checkRuleResultGroupList));
//                    warnings.stream().forEach(warn -> {
//                        // 保存对应的预警处置任务
//                        if (ObjectUtil.isNull(depart)) {
//                            log.info("当前司法所为空{}");
//                        }
//                        log.info("当前的预警数据{}，对应的司法所{}", warn.getId(), ObjectUtil.isNotEmpty(depart) ? depart.getDidepartid() : "null");
//                        Cre_work cre_work = new Cre_work(warn, depart);
//                        cre_workService.saveOrUpdate(cre_work);
//                        // 发送消息
//                        this.crc_personService.sendMessage(perid, cre_warning.getId(), cre_work.getId(), cre_warning.getType());
//                    });
                }
            }
        }
    }


    @Override
    public List<Cre_record_ga> findRecordByPersonIdsAndTime(List<String> personIds, Date startTime, Date endTime) {
        return dao.findRecordByPersonIdsAndTime(personIds, startTime, endTime);
    }

    @Override
    public List<Cre_record_ga> findRecordByTaskId(String taskId) {
        return dao.findRecordByTaskId(taskId);
    }

    /**
     * 公安数据异步同步
     * @param taskId
     */
    @Override
    public void validateRecord(String taskId) {
        // 通过taskId 查询对应的数据
        List<Cre_record_ga> record_gas = findRecordByTaskId(taskId);
        // 进行规则校验
        if (CollectionUtil.isNotEmpty(record_gas)) {
            try {
                log.info("开始公安数据校验，当前的taskId:{}", taskId);
                transRuleRequests(record_gas);
            } catch (Exception e) {
                log.error("当前批次的任务:{}执行校验失败{}", taskId, e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 公安数据同步
     * @param taskId
     * @throws Exception
     */
    @Override
    public void validateRecordAsync(String taskId) throws Exception {
        log.info("异步公安数据校验，存入taskId:{}", taskId);
        HashMap data = new HashMap();
        data.put("taskId", taskId);
        redisCacheUtil.leftPush(WarningThread.MQNAME, data);
        log.info("redis存储异步校验任务id成功：{}", taskId);
    }

    @Override
    public Long countCameraShotTotal(Crc_camera camera, Cre_record_gaPageInfo pageInfo) {
        Specification spec = this.createSpecification(pageInfo);
        Specification<Cre_record_ga> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.and(criteriaBuilder.equal(root.get("lngcamera"), camera.getLng()),
                        criteriaBuilder.equal(root.get("latcamera"), camera.getLat())))
        ).select(root.get("id")).distinct(Boolean.TRUE).getRestriction();
        return dao.count(spec.and(specification));
    }

    @Override
    public Long countCameraPersonTotal(Crc_camera camera, Cre_record_gaPageInfo pageInfo) {
        Specification spec = this.createSpecification(pageInfo);
        Specification<Cre_record_ga> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.and(criteriaBuilder.equal(root.get("lngcamera"), camera.getLng()),
                        criteriaBuilder.equal(root.get("latcamera"), camera.getLat())))
        ).select(root.get("perid")).distinct(Boolean.TRUE).getRestriction();
        return dao.count(spec.and(specification));
    }

    @Override
    public List<Cre_record_ga> recentRecordGa(String perId) {
        Pageable pageable = PageRequest.of(0, 10, Sort.by("rectime").descending());
        List<Cre_record_ga> recordGas = dao.recentRecordGa(perId, pageable);
        if (CollectionUtil.isNotEmpty(recordGas)) {
            for (Cre_record_ga ga : recordGas) {
                ga.setPhoto(haAttachmentService.getFileUrl(ga.getPhoto()));
                ga.setFacephoto(haAttachmentService.getFileUrl(ga.getFacephoto()));
            }
            return recordGas;
        }
        return Collections.emptyList();
    }

    @Override
    public Page<Cre_record_ga> getDayMonitor(Cre_record_gaPageInfo pageInfo) {
        return dao.getDayMonitor(pageInfo);
    }

    @Override
    public List<MarkPointVO> getActionTrack(Cre_record_gaPageInfo pageInfo) {
        return dao.getActionTrack(pageInfo);
    }

    @Override
    public List<MonitoringVO> getMonitoringList(Cre_record_gaPageInfo queryPageInfo) {
        return dao.getMonitoringList(queryPageInfo);
    }

//    @Override
    public List<String> getMonitoringPersonIds(Cre_record_gaPageInfo pageInfo) {
        SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startTime = sdfInput.parse(pageInfo.getF_rectime());
            Date endTime = sdfInput.parse(pageInfo.getF_rectime_01());
            return dao.getMonitoringPersons(startTime, endTime);
        } catch (ParseException e) {
            log.error("获取监控人员ID失败:{}",e.getMessage());
        }
        return null;
    }


}
